package com.gzy.rpsm_property.service.Impl;

import com.gzy.rpsm_property.mapper.ReplyMapper;
import com.gzy.rpsm_property.pojo.Message;
import com.gzy.rpsm_property.mapper.MessageMapper;
import com.gzy.rpsm_property.pojo.Messages;
import com.gzy.rpsm_property.pojo.Ms;
import com.gzy.rpsm_property.pojo.Reply;
import com.gzy.rpsm_property.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Date;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private ReplyMapper replyMapper;

    @Override
    public Message getMessageById(int messageId) {
        return messageMapper.getMessageById(messageId);
    }

    @Override
    public List<Ms> getAllMessages() {
        return messageMapper.findAllMessages();
    }

    @Override
    public List<Ms> getUserAndMessagesByUsername(String username) {
        return messageMapper.findUserAndMessagesByUsername(username);
    }

    @Override
    public void sendMessage(int userId, String content, String title) {
        Messages messages = new Messages();
        messages.setMessageUserId(userId);
        messages.setMessageContent(content);
        messages.setMessagePublishTime(new Date(System.currentTimeMillis()));
        messages.setMessageTitle(title);

        messageMapper.insertMessage(messages);
    }

    @Override
    public void updateMessage(int messageId, String messageContent, String messageTitle) {
        Message message = new Message();
        message.setMessageId(messageId);
        message.setMessageContent(messageContent);
        message.setMessageTitle(messageTitle);
        message.setMessagePublishTime(new java.sql.Date(System.currentTimeMillis()));

        messageMapper.updateMessage(message);
    }

    @Override
    public void replyToMessage(String messageId, String replyContent, String replyTitle,  String replyUserName) {
        Reply reply = new Reply();
        reply.setReplyId(UUID.randomUUID().toString()); // 生成唯一的 reply_id
        reply.setMessageId(Integer.parseInt(messageId)); // 设置 message_id
        reply.setReplyUserName(replyUserName);
        reply.setReplyMessageTitle(replyTitle);
        reply.setReplyMessageContent(replyContent);
        reply.setReplyTime(new java.sql.Date(System.currentTimeMillis()));

        replyMapper.insertReply(reply);
    }

    @Override
    public void addReply(Reply reply) {
        // 确保 reply_id 不为 null
        if (reply.getReplyId() == null) {
            reply.setReplyId(UUID.randomUUID().toString());
        }
        replyMapper.insertReply(reply);
    }

    @Override
    public List<Reply> getRepliesByMessageId(int messageId) {
        return replyMapper.getRepliesByMessageId(messageId);
    }
}
